﻿using System;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using RTMBindings.Responses;
using RTMBindings;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using System.Threading;

namespace MilkCart.ViewModel
{
    public abstract class ViewModel : ViewModelBase
    {
        protected ViewModel()
        {
            LogOnCommand = new RelayCommand(LogonCommandExecute);
        }

        protected void ExecutionFailed(Exception exception)
        {
            var msg = new DialogMessage(this, exception.Message, result => { })
            {
                Button = MessageBoxButton.OK,
                Caption = "Error executing function.",
                DefaultResult = MessageBoxResult.OK
            };

            Messenger.Default.Send(msg);
        }

        private RTMTimeline timeline;

        private ManualResetEvent getTimelineWait = new ManualResetEvent(false);

        protected RTMTimeline Timeline
        {
            get
            {
                if (Token == null)
                    return null;
                if (timeline == null)
                {
                    RTMTimelineBindings.CreateTimeline(MainPage.ApiKey, MainPage.Secret, Token, ContinueGetTimeline, ExecutionFailed);

                    getTimelineWait.WaitOne(new TimeSpan(0, 0, 5));
                }

                return timeline;
            }
        }

        private void ContinueGetTimeline(RTMTimelineResponse response)
        {
            timeline = new RTMTimeline(response.Id);
            getTimelineWait.Set();
        }

        public void LogonCommandExecute()
        {
            var msg = new NotificationMessage(NotificationMessages.SwitchToAccount);
            Messenger.Default.Send(msg);
        }

        public bool AuthenticationRequired
        {
            get { return authenticationRequired; }
            set
            {
                authenticationRequired = value;
                DispatcherHelper.CheckBeginInvokeOnUI(() => RaisePropertyChanged("AuthenticationRequired"));
            }
        }

        private RTMToken token;
        private bool authenticationRequired;
        public RelayCommand LogOnCommand { get; set; }

        public RTMToken Token
        {
            get
            {
                if (token == null)
                    token = RTMAuthBindings.RetrieveToken();

                if (token == null)
                    AuthenticationRequired = true;
                else
                    AuthenticationRequired = false;

                return token;

            }
        }
    }
}
